package produceAndConsum;

public class Consumer implements Runnable{
    synchronized void waitFull(Semaphore s) throws InterruptedException {
        s.full--;
        if(s.full<0){
            s.processlist.addLast(Thread.currentThread());
            Thread.currentThread().sleep(1000*60);
        }
    }

    synchronized void waitMutex(Semaphore s) throws InterruptedException {
        s.mutex--;
        if(s.mutex<0){
            s.mutexlist.addLast(Thread.currentThread());
            Thread.currentThread().sleep(1000*60);
        }
    }

    synchronized void signalMutex(Semaphore s){
        s.mutex++;
        if(s.mutex<=0){
            s.mutexlist.getFirst().interrupt();
            s.mutexlist.removeFirst();
        }
    }

    synchronized void signalEmpty(Semaphore s){
        s.empty++;
        if(s.empty<=0){
            s.processlist.getFirst().interrupt();
            s.processlist.removeFirst();
        }

    }

    void consum() throws InterruptedException {
        while (true){
            try {
                waitFull(Main.s);
            } catch (InterruptedException e) {
                //e.printStackTrace();
            }
            try {
                waitMutex(Main.s);
            } catch (InterruptedException e) {
                //e.printStackTrace();
            }
            Thread.sleep(2000);
            Main.buffer[Main.nextout]='0';
            Main.nextout=(Main.nextout+1)% Main.s.K;
            Main.s.count--;
            Main.s.value++;
            System.out.println(Thread.currentThread().getName()+"消费了,此时满缓冲区为:"+ Main.s.count+" 空缓冲区为:"+ Main.s.value);
            signalMutex(Main.s);
            signalEmpty(Main.s);
        }
    }

    @Override
    public void run() {
        try {
            consum();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
